<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
*/

/**
 * Handles file uploads into local filesystem
 *
 * @author chaporgin_a
 */
class VA_Form_File_Storage_LocalFS extends VA_Form_File_Storage {
    private $storageFolder = null;
    public function  __construct($options) {
        parent::__construct($options);
        $pathToStorage = $this->getOption('path', 'files');
        $forThisJoomlaSite = $this->getOption('forJoomla', TRUE);
        if( TRUE == $forThisJoomlaSite) $this->storageFolder = JPATH_COMPONENT_SITE.DIRECTORY_SEPARATOR.$pathToStorage;
        else $this->storageFolder = $pathToStorage;

        if(!file_exists($this->storageFolder)) throw new Exception(sprintf('cannot open file storage at %s', $this->storageFolder));
    }
    private function allocatePlaceFor(VA_Form_File_UploadedFile $file) {
        $filename = substr(md5(rand(1,10)),0,4).'.'.$file->filename();
        $path = $this->storageFolder.DIRECTORY_SEPARATOR.self::getPathFor($filename);
        if(!file_exists($path))
            mkdir($path, 0777, true);
        $path = $path.DIRECTORY_SEPARATOR.$filename;

        return $path;
    }
    /**
     * To find where certain file should be placed
     *
     * @param string $filename
     * @return string path in storage
     */
    private static function getPathFor($filename) {
        $h = md5($filename.rand(1, 10));
        return substr($h,0,1).DIRECTORY_SEPARATOR.substr($h,1,1);
    }
    public function Put(VA_Form_File_UploadedFile $file) {
        $place = $this->allocatePlaceFor($file);
        if( file_exists($place)) return $place;
        if( move_uploaded_file($file->tmpName(), $place)) return $place;
        throw new Exception('storage could not save file');
    }
    public function FastCopy($filename) {
        $basename = date('dHi').'.'.substr($filename, strpos($filename, '.')+1);
        $src= $this->storageFolder.DIRECTORY_SEPARATOR.self::getPathFor($filename).DIRECTORY_SEPARATOR.$filename;
        $dest = $this->storageFolder.DIRECTORY_SEPARATOR.self::getPathFor($basename);
        if(!file_exists($dest))
            mkdir($dest, 0777, true);
//    var_dump(copy($src, $dest.DIRECTORY_SEPARATOR.$basename));exit;
        if(!copy($src, $dest.DIRECTORY_SEPARATOR.$basename))
            throw new Exception('could not copy file to '.$dest.DIRECTORY_SEPARATOR.$basename);
//    rename($dest.DIRECTORY_SEPARATOR.$filename, $dest.DIRECTORY_SEPARATOR.$basename);
        return $dest.DIRECTORY_SEPARATOR.$basename;
    }
    public function Remove($filePointer) {
        if(file_exists($filePointer)) return unlink($filePointer);
        else return FALSE;
    }
    
    public static function beautifyFileName($filepointer) {
        $fname = basename($filepointer);
        if( strpos($fname, '.') < strrpos($fname, '.'))
            $fname = substr($fname, strpos($fname, '.')+1);
        return $fname;
    }
}
